package com.taplinker.client.im.rpc;

import java.net.URL;

import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;

import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.core.rpc.http.client.cache.CacheKey;
import com.taplinker.core.rpc.http.client.cache.HttpCacheDAO;
import com.taplinker.core.rpc.http.client.cache.HttpCacheItem;

public class DownloadCommand  extends SimpleBaseCommand{
	private String url;
	private Callback callBack;
	
	public DownloadCommand(String url, Callback callBack) {
		this.url = url;
		this.callBack = callBack;
	}
	
	@Override
	public Result go() {
		Result result = new Result();
		try {
			String requestUrl = url;
			if(url.contains("http://")) {
				HttpCacheItem item = HttpCacheDAO.getInstance().getFileIndexItem(CacheKey.getCacheKey(new URL(requestUrl).getPath()));
				if(item != null&&!item.isTemp()){
					requestUrl = item.getPath();
				} else{
					requestUrl = new HttpTemplate().download(url, this).object.toString();	
				}
				
			}
			result.object = requestUrl;
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@Override
	public void yes(Result result) {
		try {
			if(callBack != null) {
				Message msg = new Message();
				msg.obj = result.object;
				callBack.handleMessage(msg);
			}
			Log.d("tag", result.message);
		}catch(Exception e){
			
		}
	}

	@Override
	protected void update(long planSize, long curSize) {
		super.update(planSize, curSize);
	}
	
}
